<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="./随机颜色生成样式.css">
    <title>随机颜色生成</title>
</head>

<body>
    <h1 class="text-2xl font-bold">随机颜色生成</h1>
    <div id="color-box"></div>
    <button id="gen-btn" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
        生成随机颜色
    </button>
    <button id="copy-btn" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
        <i class="fa-solid fa-copy"></i> 复制颜色
    </button>
    <p id="color-txt" class="text-gray-700">当前颜色代码: </p>

    <script>
        const colorBox = document.getElementById('color-box');
        const genBtn = document.getElementById('gen-btn');
        const colorTxt = document.getElementById('color-txt');
        const copyBtn = document.getElementById('copy-btn');

        function genHexColor() {
            let color = '#';
            const chars = '0123456789abcdef';
            for (let i = 0; i < 6; i++) {
                color += chars[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        function updateColor() {
            const randomColor = genHexColor();
            colorBox.style.backgroundColor = randomColor;
            colorTxt.textContent = `当前颜色代码: ${randomColor}`;
        }

        copyBtn.addEventListener('click', () => {
            const code = colorTxt.textContent.split(': ')[1];
            navigator.clipboard.writeText(code).then(() => {
                alert(`已复制颜色代码: ${code}`);
            }).catch((err) => {
                console.error('复制失败: ', err);
            });
        });

        genBtn.addEventListener('click', updateColor);

        // 页面加载时生成一个随机颜色
        updateColor();
    </script>
</body>

</html>
    